package client

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net"
	"strconv"
)

const serverAddr = "192.168.1.43:11344"

func main() {
	postData()
}

func getRedirect() {
	body := "GET / HTTP/1.1\r\n" +
		"Host: book.weigou365.cn\r\n" +
		"Accept: text/html, text/plain\r\n" +
		"Accept-Encoding: compress\r\n" +
		"\r\n"

	reqmod := "REQMOD icap://192.168.1.43:11344/receive ICAP/1.0\r\n" +
		"Host: 192.168.1.43:11344\r\n" +
		"Encapsulated: req-hdr=0, null-body=" + strconv.Itoa(len(body)) + "\r\n" +
		"\r\n" +
		body

	send(reqmod)
}

func gateway() {
	body := "GET / HTTP/1.1\r\n" +
		"Host: gateway\r\n" +
		"Accept: text/html, text/plain\r\n" +
		"Accept-Encoding: compress\r\n" +
		"\r\n"

	header := "REQMOD icap://192.168.1.43:11344/receive ICAP/1.0\r\n" +
		"Host: 192.168.1.43:11344\r\n" +
		"Encapsulated: req-hdr=0, null-body=" + strconv.Itoa(len(body)) + "\r\n" +
		"\r\n"

	send(header + body)
}

func rpostData() {
	header := "GET / HTTP/1.1\r\n" +
		"Host: book.weigou365.cn\r\n" +
		"Accept: text/html, text/plain, image/gif\r\n" +
		"Accept-Encoding: gzip, compress\r\n" +
		"\r\n"
	body := "HTTP/1.1 200 OK\r\n" +
		"Date: Mon, 10 Jan 2000 09:52:22 GMT\r\n" +
		"Server: Apache/1.3.6 (Unix)\r\n" +
		"ETag: \"63840-1ab7-378d415b\"\r\n" +
		"Content-Type: text/html\r\n" +
		"Content-Length: 51\r\n" +
		"\r\n" +
		"33\r\n" +
		"This is data that was returned by an origin server.\r\n" +
		"0\r\n" +
		"\r\n"

	header := "RESPMOD icap://192.168.1.43:11344/receive ICAP/1.0\r\n" +
		"Host: 192.168.1.43:11344\r\n" +
		"Encapsulated: req-hdr=0, res-hdr=113, res-body=" + strconv.Itoa(len(body)) + "\r\n" +
		"\r\n"
	send(header + body)
}

func postData() {
	body := "POST / HTTP/1.1\r\n" +
		"Host: www.java.com\r\n" +
		"Accept: text/html, text/plain\r\n" +
		"Accept-Encoding: compress\r\n" +
		"Cache-Control: no-cache\r\n" +
		"\r\n" +
		"1e\r\n" +
		"I am posting this information.\r\n" +
		"0\r\n" +
		"\r\n"

	header :=
		"REQMOD icap://192.168.1.43:11344/receive ICAP/1.0\r\n" +
			"Host: 192.168.1.43:11344\r\n" +
			"Encapsulated: req-hdr=0, req-body=" + strconv.Itoa(len(body)) + "\r\n" +
			"\r\n"

	send(header + body)
}

func send(body string) {
	conn, err := net.Dial("tcp", serverAddr)
	if err != nil {
		log.Panic(err)
	}

	defer conn.Close()

	io.WriteString(conn, body)
	reader := bufio.NewReader(conn)
	var buf [1024]byte
	for {
		n, err := reader.Read(buf[:])
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println(string(recvStr[:n]))
	}
}
